/**
 * Description:
 * Class Name:CustomPerson
 * Date:2022/5/3 13:13
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第15章_输入输出._15_8_Java9改进的对象序列化._15_8_5_自定义序列化;

import java.io.*;

public class CustomPerson implements Serializable {
    private String name;
    private int age;

    public CustomPerson(String name, int age){
        System.out.println("有参数的构造器");
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        // 将name实例变量值反转后写入二进制流
        out.writeObject(new StringBuilder(name).reverse());
        out.writeInt(age);
    }
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
        // readObject()方法中恢复实例变量的顺序应该与writeObject()方法存储实例变量的顺序一致，否则将不能正常恢复该Java对象
        this.name = ((StringBuilder)in.readObject()).reverse().toString();
        this.age = in.readInt();
    }

    public static void main(String[] args) {
        try (
                var oos = new ObjectOutputStream(new FileOutputStream("Chapter_15_8_5_CustomPerson.txt"))
                ){
            oos.writeObject(new CustomPerson("定制的孙悟空", 500));
        }
        catch (IOException ioException){
            ioException.printStackTrace();
        }
    }
}
